package controllers

import (
	"fmt"
	"os"
	"pfl/db"
	"pfl/models"
	"pfl/utils"
	"strconv"

	"github.com/astaxie/beego"
)

const xuexiaoziping = 5

type SmallClassList []models.Smallclass

func (list SmallClassList) Len() int {
	return len(list)
}

func (list SmallClassList) Less(i, j int) bool {
	return list[i].Order < list[j].Order
}

func (list SmallClassList) Swap(i, j int) {
	list[i], list[j] = list[j], list[i]
}

var AllSmallClassList SmallClassList

func (list SmallClassList) GetNameById(id int) string {
	for _, v := range list {
		if v.Id == id {
			return v.Name
		}
	}
	return ""
}

func GetAllSmallClass() {
	err := db.Mysql.Find(&AllSmallClassList)
	if err != nil {
		os.Exit(1)
	}
}
func GetSmallClassName(id int) string {
	if id <= 0 || id > len(AllSmallClassList) {
		return ""
	}
	return AllSmallClassList[id-1].Name
}

func GetSmallBySid(sid int) *models.Smallclass {
	for k, v := range AllSmallClassList {
		if v.Id == sid {
			return &AllSmallClassList[k]
		}
	}
	return nil
}

type ListController struct {
	beego.Controller
}

func (c *ListController) BList() {
	id, _ := c.GetInt(":id")
	if id <= 0 && id > AllBigClisses.Len() {
		c.Redirect("/", 302)
		return
	}
	sid := GetFirstSmallIdByBid(id)
	if sid == -1 {
		c.Redirect("/", 302)
		return
	}
	ShowName := ""
	if sid == 0 {
		ShowName = AllBigClisses.GetNameById(id)
	} else {
		ShowName = AllSmallClassList.GetNameById(sid)
	}
	SetBigClassActive(id)
	c.Data["BigClassName"] = AllBigClisses.GetNameById(id)
	c.Data["ClassName"] = ShowName
	c.Data["Smalls"] = GetSmallsByBid(id)
	c.Data["BigId"] = id
	c.Data["SmallId"] = sid
	c.Data["Navigation"] = NavigationBar
	c.TplName = "list.html"
}

func (c *ListController) SList() {
	id, _ := c.GetInt(":id")
	bid, _ := c.GetInt(":bid")
	if id <= 0 || bid < 0 || bid > AllBigClisses.Len() {
		c.Redirect("/", 302)
		return
	}
	ms := GetSmallBySid(id)
	ShowName := ""
	if ms == nil {
		ShowName = AllBigClisses.GetNameById(bid)
	} else {
		ShowName = ms.Name
	}
	SetBigClassActive(bid)

	c.Data["BigClassName"] = AllBigClisses.GetNameById(bid)
	c.Data["ClassName"] = ShowName
	c.Data["Smalls"] = GetSmallsByBid(bid)
	c.Data["BigId"] = bid
	c.Data["SmallId"] = id
	c.Data["Navigation"] = NavigationBar
	c.TplName = "list.html"
}

func (c *ListController) SearchList() {
	slike := c.GetString("sl")
	if slike == "" {
		c.Redirect("/", 302)
		return
	}
	c.Data["Like"] = slike
	c.Data["Navigation"] = NavigationBar
	c.TplName = "listsearch.html"
}
func (c *ListController) SearchData() {
	pi, _ := c.GetInt("s")
	pc, _ := c.GetInt("c")
	slike := c.GetString("sl")
	if pi == 0 || pc == 0 || slike == "" {
		c.Ctx.ResponseWriter.Write(utils.JsonToBytes(1, 0, "12")) //没有数据
		return
	}
	details := &models.Detail{}
	CountDetails, err := db.Mysql.Where(fmt.Sprintf("Bigclassid >=0 And smallclassid >=0 And Title like '%%%s%%' ", slike)).Count(details)
	startindex := (pi - 1) * pc
	var rets []map[string][]byte
	rets, err = db.Mysql.Query(fmt.Sprintf("SELECT id FROM detail where Bigclassid >=0 And smallclassid >=0 And Title like '%%%s%%' ORDER BY updatetime desc limit ?,?", slike), startindex, pc)
	if err == nil {
		ds := make([]models.Detail, 0)
		c.Ctx.ResponseWriter.Write(utils.JsonToBytes(1, int(CountDetails), GetDetailList(rets, &ds))) //OK

	} else {
		fmt.Println(err)
		c.Ctx.ResponseWriter.Write(utils.JsonToBytes(0, 0, "")) //查询错误
	}
}

type ListData struct {
	Id         int
	Title      string
	Updatetime string
}

func GetDetailList(rets []map[string][]byte, ds *[]models.Detail) []ListData {
	ids := make([]int, len(rets))
	for k, v := range rets {
		ids[k], _ = strconv.Atoi(utils.BytesToString(v["id"]))
	}
	db.Mysql.Select("id,title,updatetime").In("id", ids).Desc("updatetime").Find(ds)
	if len(*ds) > 0 {
		LD := make([]ListData, len(*ds))
		for k, v := range *ds {
			LD[k].Id = v.Id
			LD[k].Title = v.Title
			LD[k].Updatetime = v.Updatetime.Format("2006-01-02")
		}
		return LD
	} else {
		return nil
	}

}

func (c *ListController) Get() {
	c.TplName = "list.html"
}

func (c *ListController) GetListData() {
	pi, _ := c.GetInt("s")
	pc, _ := c.GetInt("c")
	bid, _ := c.GetInt("bid")
	sid, _ := c.GetInt("sid")
	if pi == 0 || pc == 0 || bid <= 0 || bid > len(AllBigClisses) {
		c.Ctx.ResponseWriter.Write(utils.JsonToBytes(1, 0, "12")) //没有数据
		return
	}
	var CountDetails int64
	var err error
	details := &models.Detail{}
	//if name == "" {
	CountDetails, err = db.Mysql.Where("Bigclassid = ? And smallclassid = ?", bid, sid).Count(details)
	//	} else {
	//		CountDetails, err = db.Mysql.Where(fmt.Sprintf("Bigclassid = ? And  title like '%%%s%%'", name), bid).Count(details)
	//	}
	if CountDetails == 0 {
		c.Ctx.ResponseWriter.Write(utils.JsonToBytes(1, 0, "13")) //没有数据
		return
	}
	ds := make([]models.Detail, 0)
	startindex := (pi - 1) * pc
	var rets []map[string][]byte
	//	if name == "" {
	rets, err = db.Mysql.Query("SELECT id FROM detail where Bigclassid = ? And smallclassid = ? ORDER BY updatetime desc limit ?,?", bid, sid, startindex, pc)
	//	} else {
	//		rets, err = db.Mysql.Query(fmt.Sprintf("SELECT id FROM detail where Bigclassid = ? And Title like '%%%s%%' Order by updatetime DESC Limit ?,? ", name), bid, startindex, pc)
	//	}
	if err == nil {
		c.Ctx.ResponseWriter.Write(utils.JsonToBytes(1, int(CountDetails), GetDetailList(rets, &ds))) //OK
	} else {
		c.Ctx.ResponseWriter.Write(utils.JsonToBytes(0, 0, "")) //查询错误
	}
}

type List_1Data struct {
	S    models.Smallclass
	Data []models.Detail
}

func (c *ListController) List_1() {
	id, _ := c.GetInt(":id")
	if id != xuexiaoziping {
		c.Redirect("/", 302)
	}
	LD := make([]List_1Data, 0)
	for _, v := range AllSmallClassList {
		data := make([]models.Detail, 0)
		db.Mysql.Where("Bigclassid=? And SmallClassId=?", id, v.Id).Desc("updatetime").Limit(5, 0).Select("id,title,updatetime").Find(&data)
		LD = append(LD, List_1Data{S: v, Data: data})
	}
	c.Data["BigClassName"] = GetBigClassName(id)
	c.Data["BigClassId"] = id
	c.Data["Data"] = LD
	SetBigClassActive(id)
	c.Data["Bigclasslist"] = AllBigClisses[:7]
	c.Data["SmallClasslist"] = AllSmallClassList
	c.TplName = "list_1.html"
}

func (c *ListController) List_2() {
	id, _ := c.GetInt(":id")
	if id <= 0 {
		c.Redirect("/", 302)
	}
	SetBigClassActive(xuexiaoziping)
	c.Data["Sid"] = id
	c.Data["Sname"] = GetSmallClassName(id)
	c.Data["Bigclasslist"] = AllBigClisses[:7]
	c.Data["SmallClasslist"] = AllSmallClassList
	c.TplName = "list_2.html"
}

func (c *ListController) GetList_2Data() {
	pi, _ := c.GetInt("s")
	pc, _ := c.GetInt("c")
	name := c.GetString("n")
	bid, _ := c.GetInt("i")
	sid, _ := c.GetInt("sid")
	if pi == 0 || pc == 0 || bid <= 0 || bid > 7 || bid != xuexiaoziping || sid <= 0 {
		c.Ctx.ResponseWriter.Write(utils.JsonToBytes(1, 0, "")) //没有数据
		return
	}
	var CountDetails int64
	var err error
	details := &models.Detail{}
	if name == "" {
		CountDetails, err = db.Mysql.Where("Bigclassid = ? And smallclassid=?", bid, sid).Count(details)
	} else {
		CountDetails, err = db.Mysql.Where(fmt.Sprintf("Bigclassid = ? And smallclassid=? And title like '%%%s%%'", name), bid, sid).Count(details)
	}
	if CountDetails == 0 {
		c.Ctx.ResponseWriter.Write(utils.JsonToBytes(1, 0, "")) //没有数据
		return
	}
	ds := make([]models.Detail, 0)
	startindex := (pi - 1) * pc
	var rets []map[string][]byte
	if name == "" {
		rets, err = db.Mysql.Query("SELECT id FROM detail where Bigclassid = ? And smallclassid=? ORDER BY updatetime desc limit ?,?", bid, sid, startindex, pc)
	} else {
		rets, err = db.Mysql.Query(fmt.Sprintf("SELECT id FROM detail where Bigclassid = ? And smallclassid=? And Title like '%%%s%%' Order by updatetime DESC Limit ?,? ", name), bid, sid, startindex, pc)
	}

	if err == nil {
		c.Ctx.ResponseWriter.Write(utils.JsonToBytes(1, int(CountDetails), GetDetailList(rets, &ds))) //OK
	} else {
		c.Ctx.ResponseWriter.Write(utils.JsonToBytes(0, 0, "")) //查询错误
	}
}
func (c *ListController) GetSearchView() {
	name := c.GetString("n")
	if name == "" {
		c.Ctx.Redirect(302, "/")
		return
	}
	c.Data["N"] = name
	c.Data["Bigclasslist"] = AllBigClisses[:7]
	c.TplName = "list_search.html"
}
func (c *ListController) GetSearch() {
	name := c.GetString("n")
	if name == "" {
		c.Ctx.ResponseWriter.Write(utils.JsonToBytes(-1, 0, ""))
		return
	}
	pi, _ := c.GetInt("s")
	pc, _ := c.GetInt("c")
	ds := make([]models.Detail, 0)
	startindex := (pi - 1) * pc
	details := &models.Detail{}
	CountDetails, err := db.Mysql.Where(fmt.Sprintf("title like '%%%s%%'", name)).Count(details)
	if CountDetails == 0 || err != nil {
		c.Ctx.ResponseWriter.Write(utils.JsonToBytes(1, 0, "")) //没有数据
		return
	}

	rets, err := db.Mysql.Query(fmt.Sprintf("SELECT id FROM detail where Title like '%%%s%%' Order by updatetime DESC Limit ?,? ", name), startindex, pc)
	if err == nil {
		c.Ctx.ResponseWriter.Write(utils.JsonToBytes(1, int(CountDetails), GetDetailList(rets, &ds))) //OK
	} else {
		c.Ctx.ResponseWriter.Write(utils.JsonToBytes(0, 0, "")) //查询错误
	}
}
